<?php

namespace Modules\Admin\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Routing\Controller;
use App\Admin;
use Modules\Admin\Http\Requests\AdminUserRequest;
use Spatie\Permission\Models\Role;
class AdminUserController extends Controller
{
    /**
     * Display a listing of the resource.
     * @return Response
     */
    public function index()
    {
    	$admins=Admin::where('name','!=','webmaster')->paginate(5);
        return view('admin::adminuser.index',compact('admins'));
    }

    /**
     * Show the form for creating a new resource.
     * @return Response
     */
    public function create()
    {
        return view('admin::create');
    }

    /**
     * Store a newly created resource in storage.
     * @param  Request $request
     * @return Response
     */
    public function store(AdminUserRequest $request)
    {
    		$post=$request->all();
    		$post['password']=bcrypt($post['password']);
    		Admin::create($post);
    		session()->flash('success','添加成功！');
    		return redirect ()->route('adminuser.index');
    }

    /**
     * Show the specified resource.
     * @return Response
     */
    public function show()
    {
        return view('admin::show');
    }

    /**
     * Show the form for editing the specified resource.
     * @return Response
     */
    public function edit()
    {
        return view('admin::edit');
    }

    /**
     * Update the specified resource in storage.
     * @param  Request $request
     * @return Response
     */
    public function update(AdminUserRequest $request,$id)
    {
		$post=$request->all();
		$admin=Admin::find($id);
		$admin->name=$post['name'];
		$admin->nickname=$post['nickname'];
		if($request->input('password')){
			$admin->password=bcrypt($post['password']);
		}
		$admin->save();
		session()->flash('success','修改成功！');
		return redirect ()->route('adminuser.index');
    }

    /**
     * Remove the specified resource from storage.
     * @return Response
     */
    public function destroy($id)
    {
		Admin::destroy ($id);
		session()->flash('success','删除成功！');
		return redirect ()->route('adminuser.index');
    }
    public function showRole($id){
		$admin=Admin::find($id);
		//过滤掉站长，不让站长显示在角色中
		$roles=Role::where('name','!=','webmaster')->get();
    	return view('admin::adminuser.role',compact('admin','roles'));
	}
	public function addRole(Request $request,$adminid){
    	if(!$request->input('name')){
			session()->flash('danger','请至少选择一个角色！');
			return redirect ()->back();
		}
    	$admin=Admin::find($adminid);
		$admin->syncRoles($request->input('name'));
		//$admin->assignRole($request->input('name'));
		session()->flash('success','分配角色成功！');
		return redirect ()->route('adminuser.index');
	}
}
